﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Halation.Extensions
{
    /// <summary>
    /// 类型扩展
    /// </summary>
    public static class TypeEx
    {
        /// <summary>
        /// 获取自定义特性
        /// </summary>
        /// <typeparam name="A">特性类型</typeparam>
        /// <param name="type">要查找的类型</param>
        /// <param name="inherit">是否继承</param>
        /// <returns>特性的枚举</returns>
        public static IEnumerable<A> GetCustomAttributes<A>(this Type type, bool inherit) where A : Attribute
        {
            var attrs = type.GetCustomAttributes(typeof(A), inherit);
            if (attrs.Length == 0) yield return null;
            foreach (A item in attrs) yield return item;
        }
        /// <summary>
        /// 获取自定义特性
        /// </summary>
        /// <typeparam name="A">特性类型</typeparam>
        /// <param name="type">要查找的类型</param>
        /// <param name="inherit">是否继承</param>
        /// <returns>特性的实例</returns>
        public static A GetCustomAttribute<A>(this Type type, bool inherit) where A : Attribute
        {
            var attrs = type.GetCustomAttributes(typeof(A), inherit);
            if (attrs.Length != 1) return null;
            return attrs.FirstOrDefault() as A;
        }
    }
}
